package com.bill99.rpc.cluster.loadbalance;

import com.bill99.rpc.cluster.LoadBalance;
import com.bill99.rpc.common.Constants;
import com.bill99.rpc.registry.url.ServiceUrl;

/**
 * @author sheng.zhang
 */
public abstract class AbstractLoadBalance implements LoadBalance {

	/**
	 * @param serviceUrl
	 * @return
	 */
	protected int getWeight(ServiceUrl serviceUrl) {
		int weight=serviceUrl.getParameter(Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
		if (weight > 0) {
			long timestamp = serviceUrl.getParameter(
					Constants.TIMESTAMP_KEY, 0L);
			if (timestamp > 0L) {
				int uptime = (int) (System.currentTimeMillis() - timestamp);
				int warmup = serviceUrl.getParameter(
						Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
				if (uptime > 0 && uptime < warmup) {
					weight = calculateWarmupWeight(uptime, warmup, weight);
				}
			}
		}
		return weight;
	}

	static int calculateWarmupWeight(int uptime, int warmup, int weight) {
		int ww = (int) (uptime / ((float) warmup / (float) weight));
		return ww < 1 ? 1 : (ww > weight ? weight : ww);
	}

}
